﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Routing;

namespace Clover.BaseAuth
{
    public class PermissionFilter :Attribute,  IAuthenticationFilter
    {
        public string Url { get; set; }
        public PermissionFilter() { }

        public PermissionFilter(string url)
        {
            Url = url;
        }

        public void OnAuthentication(AuthenticationContext filterContext)
        {
            //无需验证权限页面
            bool skipAuthentication = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthentication)
            {
                return;
            }

            //加载用户所有权限并写入存储器
            PermissionCacheSerializer.SavePermissions(filterContext, filterContext.ActionDescriptor);

            //验证权限
            if (!PermissionValidtor.Validate(filterContext.ActionDescriptor))
            {
                if (!string.IsNullOrEmpty(Url))
                {
                    filterContext.Result = new RedirectResult(Url); 
                }
                else
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                }
            }
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) { }
    }
}
